package com.yuhj.cateyemovie.fragment;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.apache.http.client.entity.UrlEncodedFormEntity;

import com.baidu.mapapi.map.MapViewLayoutParams.ELayoutMode;
import com.lidroid.xutils.BitmapUtils;
import com.yuhj.cateyemovie.R;
import com.yuhj.cateyemovie.adapter.PlayingMovieAdapter;
import com.yuhj.cateyemovie.bean.Advertisement;
import com.yuhj.cateyemovie.bean.PlayingMovieList;
import com.yuhj.cateyemovie.clients.ClientApi;
import com.yuhj.cateyemovie.interfaces.AdvertisementCallback;
import com.yuhj.cateyemovie.interfaces.PlayingMovieCallback;
import com.yuhj.cateyemovie.utils.LoadingAinm;
import com.yuhj.cateyemovie.widget.PullToRefreshLayout;
import com.yuhj.cateyemovie.widget.PullToRefreshLayout.OnRefreshListener;

import android.R.bool;
import android.R.integer;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.util.LruCache;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewDebug.FlagToString;
import android.view.ViewGroup;
import android.view.ViewDebug.FlagToString;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @name PalyingFragmeng
 * @Descripation 正在上映的Fragment<br>
 * @author 禹慧军
 * @date 2014-10-31
 * @version 1.0
 */
public class PalyingFragment extends Fragment implements OnRefreshListener {
	private ViewPager viewPager; // android-support-v4中的滑动组件
	private List<ImageView> imageViews; // 滑动的图片集合
	private ListView listView;
	private String[] titles; // 图片标题
	private TextView tv_title;
	private int currentItem = 0; // 当前图片的索引号
	private int[] Num = null;
	private int Count = 0;
	private ScheduledExecutorService scheduledExecutorService;
	private PlayingMovieAdapter adapter;
	private PullToRefreshLayout refreshPullToRefreshLayoutManager;
	private static final int INIT = 0;
	private static final int REFRESH = 1;
	private RelativeLayout loadrRelativeLayout;
	private LinearLayout dataLinearLayout;
	private BitmapUtils bitmapUtils;
	private ArrayList<PlayingMovieList> list = new ArrayList<PlayingMovieList>();
	private String city = "北京";
	private String Url = "http://api.mobile.meituan.com/dianying/v4/movies.json?tp=hot&order=show_desc&ct="
			+ city
			+ "&utm_campaign=AmovieBmovieCD-1&movieBundleVersion=100&utm_source=jiuyao&utm_medium=android&utm_term=100&utm_content=865061021015330&ci=1&uuid=0C70BD71F236CD098446938FF0C001CC7F879E5BC046187CC4CA8C99BA0E39C7";
	private LruCache<String, Bitmap> lruCache;
	private boolean falg = true;
	private int imageLength;

	public PalyingFragment() {

	}

	private Handler getDateHandler = new Handler() {
		@SuppressWarnings("unchecked")
		public void handleMessage(Message msg) {
			if (msg.obj == null) {
				loadrRelativeLayout.setVisibility(View.GONE);
				Toast.makeText(getActivity(), "网络异常,请检查！", 1).show();

			} else {
				if (msg.what == INIT) {
					loadrRelativeLayout.setVisibility(View.GONE);
					dataLinearLayout.setVisibility(View.VISIBLE);
					list.clear();
					list = (ArrayList<PlayingMovieList>) msg.obj;
					adapter.BindData(list);
					listView.setAdapter(adapter);
					adapter.notifyDataSetChanged();

				}
				if (msg.what == REFRESH) {

					list.clear();
					list = (ArrayList<PlayingMovieList>) msg.obj;
					adapter.BindData(list);
					listView.setAdapter(adapter);
					refreshPullToRefreshLayoutManager
							.refreshFinish(PullToRefreshLayout.SUCCEED);
					System.out.println("------刷新完毕--->");
					adapter.notifyDataSetChanged();
				}
			}
		}
	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.playing_fragment, null, false);
		listView = (ListView) view.findViewById(R.id.playing_listview);
		View hedaer = headerView();
		if (hedaer != null) {
			listView.addHeaderView(headerView());
		}
		adapter = new PlayingMovieAdapter(getActivity());
		dataLinearLayout = (LinearLayout) view
				.findViewById(R.id.linearyaoutplaying);
		loadrRelativeLayout = (RelativeLayout) view
				.findViewById(R.id.lodingRelativeLayout);

		((PullToRefreshLayout) view.findViewById(R.id.refresh_view))
				.setOnRefreshListener(this);
		LoadingAinm.ininLodingView(view);
		loadrRelativeLayout.setVisibility(View.VISIBLE);
		init();
		
		return view;
	}

	private void init() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				ClientApi.getPlayingMovieData(Url,"first",new PlayingMovieCallback() {

					public void getresult(ArrayList<PlayingMovieList> result) {
						Message msg = Message.obtain();
						msg.obj = result;
						msg.what = INIT;
						// ClientApi.getAdvertisement();
						getDateHandler.sendMessage(msg);

					}
				});
			}
		}).start();
	}

	View headerView() {
		final View view = LayoutInflater.from(getActivity()).inflate(
				R.layout.imagebox, null);
		final ArrayList<Fragment> fragments = new ArrayList<Fragment>();
		bitmapUtils = new BitmapUtils(getActivity());
		new Thread(new Runnable() {

			@Override
			public void run() {

				ClientApi.getAdvertisement(new AdvertisementCallback() {

					@Override
					public void getresult(ArrayList<Advertisement> result) {
						if (result != null) {
							imageLength=result.size()*2-1;
							int len = result.size();

							Num = new int[2 * len - 1];
							for (int i = 0; i < Num.length; i++) {
								if (i < len) {
									Num[i] = i;
								} else {
									Num[i] = 2 * len - 2 - i;
								}

							}

							titles = new String[len];
							imageViews = new ArrayList<ImageView>();
							for (int i = 0; i < result.size(); i++) {
								titles[i] = result.get(i).getName();
							}
							// 初始化图片资源
							for (int i = 0; i < len; i++) {

								fragments.add(new ImageFragment(result.get(i)
										.getImg(), getActivity()));

							}
							tv_title = (TextView) view
									.findViewById(R.id.tv_title);
							tv_title.setText(titles[0]);//
							viewPager = (ViewPager) view.findViewById(R.id.vp);
							viewPager.setAdapter(new ImagePageAdapter(
									getChildFragmentManager(), fragments));// 设置填充ViewPager页面的适配器
							// 设置一个监听器，当ViewPager中的页面改变时调用
							viewPager
									.setOnPageChangeListener(new MyPageChangeListener());
						}
					}
				});

			}

		}).start();

		return view;

	}

	public void onStart() {
	
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				while(falg){
					try {
						Thread.sleep(3000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					if (imageLength>0) {
						
					
					    Count++;
						currentItem = Num[(Count)%imageLength];
						//System.out.println("---"+imageLength+"-curretn :>" + currentItem);
						// handler.obtainMessage().sendToTarget(); //
						// 通过Handler切换图片
						
						Message msg = Message.obtain();
						msg.obj = currentItem;
						handler.sendMessage(msg);
					}
				}
			}
		}).start();
		
		super.onStart();
		
		
	}

	@Override
	public void onStop() {
		// 当Activity不可见的时候停止切换
		falg=false;
		super.onStop();
	}                                                                 
	// 切换当前显示的图片
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			viewPager.setCurrentItem((Integer) msg.obj);
		};
	};

	/**
	 * 当ViewPager中页面的状态发生改变时调用
	 * 
	 * @author Administrator
	 * 
	 */
	private class MyPageChangeListener implements OnPageChangeListener {

		/**
		 * This method will be invoked when a new page becomes selected.
		 * position: Position index of the new selected page.
		 */
		public void onPageSelected(int position) {
			tv_title.setText(titles[position]);
			currentItem = position;
		}

		public void onPageScrollStateChanged(int arg0) {

		}

		public void onPageScrolled(int arg0, float arg1, int arg2) {

		}
	}

	/**
	 * 填充ViewPager页面的适配器
	 * 
	 * @author Administrator
	 * 
	 */
	private class ImagePageAdapter extends FragmentPagerAdapter {
		private ArrayList<Fragment> data;

		public ImagePageAdapter(FragmentManager fm, ArrayList<Fragment> data) {
			super(fm);
			this.data = data;
		}

		@Override
		public Fragment getItem(int arg0) {
			return data.get(arg0);
		}

		@Override
		public int getCount() {
			return data.size();
		}

	}

	private interface CallBack {

		public void getResult();
	}

	@Override
	public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
		refreshPullToRefreshLayoutManager = pullToRefreshLayout;
		System.out.println("---------执行刷新->");
		new Thread(new Runnable() {

			@Override
			public void run() {

				ClientApi.getPlayingMovieData(Url,"first",new PlayingMovieCallback() {

					public void getresult(ArrayList<PlayingMovieList> result) {
						Message msg = Message.obtain();
						msg.obj = result;
						msg.what = REFRESH;
						if (msg.obj != null) {
							System.out.println("-------下载数据-->");
						}
						// getDateHandler.sendMessage(msg);
						getDateHandler.sendMessageDelayed(msg, 3000);

					}
				});

			}
		}).start();
	}

	@Override
	public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
		pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.FAIL);

	}

}
